import requests

def get_weather(city_name, api_key):
    """调用高德天气 API 获取指定城市的天气信息"""
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?city={city_name}&key={api_key}&extensions=all"

    try:
        # 发起 GET 请求
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功
    except requests.exceptions.RequestException as e:
        return f"Error occurred while fetching weather data: {e}"

    if response.status_code == 200:
        # 获取返回的 JSON 数据
        data = response.json()

        # 打印返回的完整数据，检查API返回的结构
        print("API Response Data:", data)

        # 检查API状态码是否为成功状态
        if data.get("status") == "1":  # 成功获取天气数据
            # 获取 forecasts 字段中的天气数据
            forecasts = data.get("forecasts", [])
            if not forecasts:
                return f"未找到{city_name}的天气数据，可能是城市名称不正确或者API不支持该城市。"

            forecast_data = forecasts[0]  # 获取第一个城市的天气预报
            city = forecast_data.get("city", city_name)  # 城市名称
            province = forecast_data.get("province", "Unknown")  # 省份
            report_time = forecast_data.get("reporttime", "Unknown")  # 天气报告时间
            casts = forecast_data.get("casts", [])  # 获取天气预报的详细信息

            if not casts:
                return f"没有天气预报数据。"

            # 获取今天的天气信息（取第一个）
            today_weather = casts[0]
            date = today_weather.get("date", "Unknown")  # 日期
            week = today_weather.get("week", "Unknown")  # 星期
            day_weather = today_weather.get("dayweather", "Unknown")  # 白天气象
            night_weather = today_weather.get("nightweather", "Unknown")  # 夜间气象
            day_temp = today_weather.get("daytemp", "Unknown")  # 白天气温
            night_temp = today_weather.get("nighttemp", "Unknown")  # 夜间气温
            day_wind = today_weather.get("daywind", "Unknown")  # 白天风向
            night_wind = today_weather.get("nightwind", "Unknown")  # 夜间风向
            day_wind_power = today_weather.get("daypower", "Unknown")  # 白天风力
            night_wind_power = today_weather.get("nightpower", "Unknown")  # 夜间风力

            # 返回天气信息
            weather_info = (
                f"{city} ({province}) 的天气预报：\n"
                f"报告时间: {report_time}\n"
                f"日期: {date} (星期{week})\n"
                f"白天气象: {day_weather}\n"
                f"夜间气象: {night_weather}\n"
                f"白天气温: {day_temp}°C\n"
                f"夜间气温: {night_temp}°C\n"
                f"白天风向: {day_wind}, 风力: {day_wind_power}\n"
                f"夜间风向: {night_wind}, 风力: {night_wind_power}\n"
            )
            return weather_info
        else:
            # 返回API错误信息
            return f"高德天气API返回错误：{data.get('info', 'Unknown error')}"
    else:
        return "无法获取天气数据，可能是请求失败。"


def validate_api_key(api_key):
    """验证 API Key 是否有效"""
    url = f"https://restapi.amap.com/v3/weather/weatherInfo?city=101010100&key={api_key}&extensions=base"  # 北京的城市代码
    try:
        # 发起请求
        response = requests.get(url)
        response.raise_for_status()  # 检查请求是否成功
        # 如果返回状态码为 200，表示请求成功
        if response.status_code == 200:
            data = response.json()
            if data["status"] == "1":  # 判断返回的数据中是否包含有效的天气信息
                print("API Key 验证成功！")
                return True
            else:
                print(f"API 返回错误：{data.get('info', '未知错误')}")
                return False
        else:
            print(f"请求失败，状态码：{response.status_code}")
            return False
    except requests.exceptions.RequestException as e:
        print(f"请求错误：{str(e)}")
        return False


if __name__ == "__main__":
    # 测试 API Key
    api_key = "8aec8c15e402cf89d93e5f3c22a74104"
    if validate_api_key(api_key):
        print("API Key 是有效的。")
    else:
        print("API Key 无效或请求失败。")
    print(get_weather('杭州', api_key=api_key))
